package com.demo.project_template.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.project_template.entity.LoginUser;
import com.demo.project_template.entity.SysUser;
import com.demo.project_template.exception.ErrorCodeException;
import com.demo.project_template.exception.ErrorCodeExceptionEnum;
import com.demo.project_template.mapper.SysMenuMapper;
import com.demo.project_template.mapper.SysUserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;


/**
 * @author yyl25
 */
@Service
public class SysUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) {
        //根据用户名查询用户信息
        SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername,username));
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(user)){
            throw new ErrorCodeException(ErrorCodeExceptionEnum.USER_ERROR);
        }
        //根据用户查询权限信息 添加到LoginUser中
        Set<String> permissionKeyList  = sysMenuMapper.selectPermsByUserId(user.getId());
        //封装成UserDetails对象返回
        return new LoginUser(user,permissionKeyList);
    }
}

